import React, { useState } from "react"

import {
    Button,
    Switch,
    Select,
    message,
} from 'antd'

import { HpaInfo, AppHpas, Cluster } from './interfaces'
import ContainerRow from '../../components/ContainerRow'
import CElastictyList from "./c_elasticity_list";
import store from "./store"
import "./c_elasticity.less"
const { Option } = Select;


// 弹性策略
interface IElasticity {
    visible: boolean//是否启用  1关闭   2启用
    appClusterList: Array<Cluster>
    hpaList: AppHpas
    params: { //参数
        [key: string]: string
    }
    onClick(value: object): void
}

const Elasticity: React.FC<IElasticity> = (props) => {
    const { onClick, hpaList, appClusterList } = props
    const [visible, setVisible] = useState(props.visible)//是否启用
    const [cpu, setCpu] = useState(hpaList.cpu)
    const [mem, setMem] = useState(hpaList.mem)
    const [strategy, setStrategy] = useState(
        cpu.length ? (mem.length ? [1, 2] : [1]) : (mem.length ? [2] : [])
    )//是否选择策略 *暂定
    const [rule, setRule] = useState(false)//规则非空验证
    const hpaInfo = (type: string): HpaInfo => ({
        app_id: props.params.app_id,
        metric_type: type,
        val_type: 1,
        expr_value: 1,
        start_time: Date.now(),
        end_time: Date.now() + 86400000,
        min_num: 1,
        max_num: 1,
        expr_time: 10,
        is_delete: 0,
        cluster_labels: ''
    })


    // 添加
    const add = (type: 'cpu' | 'mem', i?: number): void => {
        if (type === 'cpu') {
            let arr = [...cpu]
            arr.splice(i !== undefined ? i + 1 : 0, 0, hpaInfo(type))
            setCpu(arr)
        } else {
            let arr = [...mem]
            arr.splice(i !== undefined ? i + 1 : 0, 0, hpaInfo(type))
            setMem(arr)
        }
    }

    //删除
    const del = (type: string, index: number): void => {
        if (type === 'cpu') {
            if (cpu.length === 1) return;
            setCpu(cpu.filter((item, i) => index !== i))
        } else {
            if (mem.length === 1) return;
            setMem(mem.filter((item, i) => index !== i))
            if (!cpu.length && !mem.length) setStrategy([])
            else if (!mem.length) setStrategy([1]);
        }
    }

    // 提交
    const submit = (): void => {
        // 校验中 - 如果是开启就验证，否则就不验证
        if (visible) {
            if (!strategy) return setRule(true);
            let msg = '' //错误提示
            const datas = [...cpu, ...mem]
            datas.forEach(item => {
                if (item.min_num > item.max_num) msg = '最大实例数不可低于最小实例数'
                datas.forEach(({ start_time, end_time }) => {
                    if (!isDates(item.start_time, item.end_time, start_time, end_time)) msg = '触发时间不可重合'
                })
            })

            if (msg) {
                message.error(msg)
                return;
            }
        }

        // 校验通过 - 报错样式恢复正常
        setRule(false);
        onClick({
            app_id: props.params.app_id,
            hpa_type: visible ? 1 : 0,
            hpa: [...cpu, ...mem]
        })
    }

    //时间段校验
    const isDates = (start: number, end: number, min: number, max: number): boolean => {
        if (start > min && end < max) return false
        if (start < max && end > max) return false
        if (start < min && end > min) return false
        return true
    }

    return (
        <>
            {/* 是否开启 */}
            <ContainerRow title='是否开启'>
                <Switch defaultChecked={visible} onChange={value => setVisible(value)} />
            </ContainerRow>
            {/* 弹性策略 */}
            <div className={visible ? "switch-visible" : "switch-visible v-active"}>
                <ContainerRow title='添加规则' required={!rule}>
                    <Select
                        mode="multiple"
                        allowClear
                        style={{ width: '100%' }}
                        placeholder="请选择"
                        defaultValue={strategy}
                        onFocus={() => setRule(false)}
                        onChange={(value: number[]): void => {
                            if (!value.length) return setStrategy([]);
                            setStrategy([...value])
                            // 判断有没有内容，有内容则返回
                            //如果是没有内容的初始化那么点击的时候则给他添加初始内容
                            if ((!cpu.length) && value.indexOf(1) !== -1) add('cpu');
                            if ((!mem.length) && value.indexOf(2) !== -1) add('mem');
                        }}>
                        <Option value={1}>CPU策略</Option>
                        <Option value={2}>内存策略</Option>
                    </Select>
                </ContainerRow>

                {/* 添加规则 */}
                {strategy.indexOf(1) !== -1 && cpu.map((item: HpaInfo, i) => (<div className={cpu.length ? "switch-rule" : "switch-rule v-active"} key={i}>
                    <CElastictyList type={'cpu'} item={item} appClusterList={appClusterList}
                        add={() => add('cpu', i)} del={() => del('cpu', i)} onChange={val => {
                            cpu[i] = val
                            setCpu([...cpu])
                            console.log(...cpu);
                        }} />
                </div>)
                )}
                {strategy.indexOf(2) !== -1 && mem.map((item: HpaInfo, i) => (<div className={mem.length ? "switch-rule" : "switch-rule v-active"} key={i}>
                    <CElastictyList type={'mem'} item={item} appClusterList={appClusterList}
                        add={() => add('mem', i)} del={() => del('mem', i)} onChange={val => {
                            mem[i] = val
                            setMem([...mem])
                            console.log(mem);
                        }} />
                </div>)
                )}
            </div>
            <Button type="primary" className='switch-submit' onClick={submit}>保存</Button>
        </>
    )
}



export default Elasticity;